/* 
 *  Copyright 2009-2010 Michal Trzcinka
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software distributed
 *  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 *  CONDITIONS OF ANY KIND, either express or implied. See the License for the
 *  specific language governing permissions and limitations under the License.
 */
YAHOO.namespace('TRZCINKA.VCARD');

(function() {

  var Dom = YAHOO.util.Dom,
  Lang = YAHOO.lang,
  DDProxy = YAHOO.util.DDProxy,
  Event = YAHOO.util.Event,
  Constants = YAHOO.TRZCINKA.VCARD.Constants,
  Config = YAHOO.TRZCINKA.VCARD.Config,
  Tooltip = YAHOO.widget.Tooltip,
  LOGGER = new YAHOO.widget.LogWriter('item.js');

  /**
   * DDPlayer. Item internally instantiates it to perform drag&drop.
   */
  YAHOO.TRZCINKA.VCARD.DDPlayer = function(id, sGroup, config, cell, gridModel) {
    YAHOO.TRZCINKA.VCARD.DDPlayer.superclass.constructor.apply(this, [id, sGroup, config]);
    this.initConstraints(config.regionId);
    this._cell = cell;
    this._gridModel = gridModel;
    this.initPlayer(id, sGroup, config);
  };

  YAHOO.extend(YAHOO.TRZCINKA.VCARD.DDPlayer, DDProxy, {
    initConstraints: function(regionId) {
      var region = Dom.getRegion(regionId);
      var el = this.getEl();

      Event.onContentReady(el.id, function() {
        var xy = Dom.getXY(el);

        var width = parseInt(Dom.getStyle(el, 'width'), 10);
        var height = parseInt(Dom.getStyle(el, 'height'), 10);

        var left = xy[0] - region.left;
        var right = region.right - xy[0] - width;
        var top = xy[1] - region.top;
        var bottom = region.bottom - xy[1] - height;

        this.setXConstraint(left, right);
        this.setYConstraint(top, bottom);
      }, this, true);

    },

    initPlayer: function(id, sGroup, config) {
      this.startPos = Dom.getXY(this.getEl());
      this.isTarget = false;
      this.startCell = this._cell;
    },

    startDrag: function() {
    //LOGGER.log('startdrag ' + Lang.dump(this._cell.location));
    },

    onDrag: function() {
    //LOGGER.log('ondrag ' + Lang.dump(this._cell.location));
    },

    onMouseDown: function(e) {
      //LOGGER.log('mousedown ' + Lang.dump(this._cell.location));
      LOGGER.log('this el: ' + Lang.dump(Dom.getXY(this.getEl())));
      this.moveAll = e.shiftKey;
    },

    onDragDrop: function(e, id) {
      LOGGER.log('dragdrop clientX: ' + e.clientX + ', clientY: ' + e.clientY);
      var td = Dom.get(id);

      if (!td) {
        Dom.setXY(this.getEl(), this.startPos);
        return;
      }

      var oldLocation = this.startCell.location;
      var newLocation = td.id.fromGridLocation();
      if (oldLocation.equals(newLocation) || !this._gridModel.canMove(oldLocation, newLocation)) {
        Dom.setXY(this.getEl(), this.startPos);
      } else {
        if (this.moveAll && this._gridModel.isStack(oldLocation)) {
          this._gridModel.moveStack(oldLocation, newLocation);
        } else {
          var newLocationTopItem = this._gridModel.getTopItem(newLocation);
          var order = newLocationTopItem ? newLocationTopItem.order + 1 : 1;
          this._gridModel.moveItem(oldLocation, newLocation, order);
        }
        this.startPos = Dom.getXY(this.getEl());
      }
    },

    onInvalidDrop: function() {
      LOGGER.log('invaliddrop ' + Lang.dump(this._cell.location));
      Dom.setXY(this.getEl(), this.startPos);
    } ,

    endDrag: function() {
      LOGGER.log('enddrag ' + Lang.dump(this._cell.location));
    }

  });

  /**
   * Item.
   */
  YAHOO.TRZCINKA.VCARD.Item = function(gridModel, cell, data) {
    this._gridModel = gridModel;
    this._cell = cell;
    
    this.htmlElement = document.createElement('div');
    Dom.addClass(this.htmlElement, 'cell');
    Dom.setStyle(this.htmlElement, 'height', (Config.CELL_HEIGHT - Config.ITEM_PADDING) + 'px');
    Dom.setStyle(this.htmlElement, 'width', (Config.CELL_WIDTH - Config.ITEM_PADDING) + 'px');
    Dom.setStyle(this.htmlElement, 'backgroundColor', data.backgroundColor);
    Dom.setStyle(this.htmlElement, 'color', data.foregroundColor);

    if (data.isHighlighted) {
      this._enableHighlight();
      this._isHighlighted = true;
    } else {
      this._isHighlighted = false;
    }
    this.htmlElement.innerHTML = data.text;

    var that = this;

    if (gridModel.accountType.canEditGrid()) {
      Event.on(this.htmlElement, 'click', function(e) {
        if (gridModel.getMode() == Constants.MODE_NORMAL) {
          that._showEditor();
        } else if (gridModel.getMode() == Constants.MODE_LINKING) {
          gridModel.finishLinking(that._cell.location);
        }
      });
    
      this._dd = new YAHOO.TRZCINKA.VCARD.DDPlayer(this.htmlElement, Constants.DD_GROUP, {
        regionId: Constants.TABLE_ID
      }, cell, gridModel);  
    }

    Event.onContentReady(this.htmlElement.id, this._createTooltipIfNeeded, this, true);
    
  }

  YAHOO.TRZCINKA.VCARD.Item.prototype._showEditor = function() {
    var content = this.htmlElement.innerHTML;

    var that = this;
    YAHOO.TRZCINKA.VCARD.Item._editor.show(content, function(newContent) {
      that._gridModel.updateItem(that._cell.location, {
        text: newContent
      });
    });
  };

  YAHOO.TRZCINKA.VCARD.Item.prototype.destroy = function() {
    this._destroyTooltip();
    this.htmlElement.parentNode.removeChild(this.htmlElement);
    if (this._dd) {
      this._dd.unreg();
    }
    if (this._highlightTimer) {
      this._disableHighlight();
    }
    Event.purgeElement(this.htmlElement, true);
  };

  YAHOO.TRZCINKA.VCARD.Item.prototype.updated = function(data) {
    this._destroyTooltip();
    if (data.backgroundColor) {
      Dom.setStyle(this.htmlElement, 'background-color', data.backgroundColor);
    }
    if (data.foregroundColor) {
      Dom.setStyle(this.htmlElement, 'color', data.foregroundColor);
    }
    if (data.text) {
      this.htmlElement.innerHTML = data.text;
    }
    if (typeof data.isHighlighted != undefined && data.isHighlighted != this._isHighlighted) {
      if (data.isHighlighted) {
        this._enableHighlight();
      } else {
        this._disableHighlight();
      }
    }
    this._createTooltipIfNeeded();
  };

  YAHOO.TRZCINKA.VCARD.Item.prototype._enableHighlight = function() {
    if (!this._isHighlighted) {
    this.htmlElement.style.borderWidth = Config.HIGHLIGHT_WIDTH + 'px';
      this.htmlElement.style.borderColor = Config.HIGHLIGHT_COLOR;
      var doHighlight = function() {
        this.style.borderWidth = this.style.borderWidth === Config.HIGHLIGHT_WIDTH + 'px' ? '1px' : Config.HIGHLIGHT_WIDTH + 'px';
      };
      this._highlightTimer = Lang.later(Config.HIGHLIGHT_INTERVAL, this.htmlElement, doHighlight, null, true);
      this._isHighlighted = true;
    }
  };

  YAHOO.TRZCINKA.VCARD.Item.prototype._disableHighlight = function() {
    if (this._isHighlighted) {
    this._highlightTimer.cancel();
      this._highlightTimer = null;
      this.htmlElement.style.borderWidth = '1px';
      this.htmlElement.style.borderColor = 'black';
      this._isHighlighted = false;
    }
  };

  YAHOO.TRZCINKA.VCARD.Item.prototype._createTooltipIfNeeded = function() {
   if (this.htmlElement.scrollWidth > this.htmlElement.offsetWidth ||
      this.htmlElement.scrollHeight > this.htmlElement.offsetHeight) {
      this._tooltip = new Tooltip(Dom.generateId(), {
        context: this.htmlElement,
        text: this.htmlElement.innerHTML
      });
    }
  }

  YAHOO.TRZCINKA.VCARD.Item.prototype._destroyTooltip = function() {
    if (this._tooltip) {
      this._tooltip.destroy();
      this._tooltip = null;
    }
  }

})();
